<?php
/*
 * CLI_Progress
 * Author: Jack Hirsch
 * Reason: I'm sick of waiting without knowing what's going on...
 * Usage:
 * 	$totalRows = 427;
 * 	CLI_Progress::progressBar($totalRows);
 * 	for ($i=0; $i < $totalRows; $i++) { 
 * 		//some operation
 * 		usleep(50000);
 * 		CLI_Progress::progressBarBottom();
 * 	}
 * 
 * 
*/

class CLI_Progress {
	
	private static $total;
	private static $increment;
	private static $time;
	private static $count;
	private static $itemStart;
	// --------------------------------------------------------------------
	/**
	 * Function: progressBar
	 * Description: starts a CLI progress par counter
	 * Arguments: $total is required, $increment is optional
	 */
	public static function progressBar($total, $increment = 0) {
		self::$total = $total;
		if ($increment) {
			self::$increment = $increment;
		} else {
			$increment = round($total/100);
			if ($increment < 1) {
				$increment = 1;
			}
			self::$increment = $increment;
			
		}
		self::$time = 0;
		self::$count = 1;
	}
	
	// --------------------------------------------------------------------
	/**
	 * Function: progressBarBottom
	 * Description: To be included at the bottom of the operational loop
	 */
	public static function progressBarBottom() {
		if (self::$count > 1) {
			$item_end = microtime(true);
			$item_time = $item_end - self::$itemStart;
			self::$time += $item_time;
			
		}
		
		self::$itemStart = microtime(true);
		self::$count++;
		if (self::$count % self::$increment == 0) {
			
			$numpercent = round(self::$count / self::$total * 100);
			$percent = str_pad($numpercent,3,' ', STR_PAD_LEFT);
			$avg_time = self::$time / self::$count;
			$remaining_time = round((self::$total - self::$count) * $avg_time).' seconds remain';
			$remaining_time = str_pad($remaining_time, 25, ' ', STR_PAD_RIGHT);
			$string = substr("$percent% - $remaining_time",0,35);
			$string = str_pad($string, 35, ' ', STR_PAD_RIGHT);
			$stars = '';
			for ($i=0; $i < $percent; $i++) { 
				$stars .= '*';
			}
			$stars = '|'.str_pad($stars, 100, ' ', STR_PAD_RIGHT).'|';
			echo ' '.$stars.$string;
			for ($i=0; $i < 138; $i++) {
				echo "\010";
			}
		}
	}
}
?>